package com.ccy.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccy.common.utils.PageUtils;
import com.ccy.common.utils.Query;
import com.ccy.product.dao.BrandDao;
import com.ccy.product.entity.BrandEntity;
import com.ccy.product.entity.CategoryBrandRelationEntity;
import com.ccy.product.service.BrandService;
import com.ccy.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Transactional
@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key = (String) params.get("key");
        LambdaQueryWrapper<BrandEntity> queryWrapper = Wrappers.<BrandEntity>lambdaQuery()
                .eq(StringUtils.isNotBlank(key), BrandEntity::getBrandId, key)
                .or().like(StringUtils.isNotBlank(key), BrandEntity::getName, key);
        IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public void updateDetail(BrandEntity brand) {
        this.updateById(brand);
        //保证冗余字段一致性
        if (StringUtils.isNotEmpty(brand.getName())) {
            // 同步更新其他关联数据
            LambdaUpdateWrapper<CategoryBrandRelationEntity> updateWrapper = Wrappers.<CategoryBrandRelationEntity>lambdaUpdate()
                    .set(CategoryBrandRelationEntity::getBrandName, brand.getName())
                    .eq(CategoryBrandRelationEntity::getBrandId, brand.getBrandId());
            categoryBrandRelationService.update(updateWrapper);

            // TODO 更新其他关联
        }
    }

}